from calc.models import Ts
from django.http import HttpResponse, JsonResponse
from common.page_util import page_util, page_low_util
import json
import uuid


# 获取虚拟机对应37账号
def find_ts(request):
    pcname = request.GET['pcname']
    ts_list = Ts.objects.all().filter(pcname=pcname, state='1')
    result = ""
    for i in ts_list:
        result = result + i.qhname + "|"
    return HttpResponse(result)


def ts_page(request):
    data = json.loads(request.body)
    page = data['page']
    limit = data['limit']
    params = data['params']
    qhname = params['qhname']
    pcname = params['pcname']
    if qhname != '':
        if pcname != '':
            ts_list = Ts.objects.all().filter(qhname=qhname, pcname=pcname)
        else:
            ts_list = Ts.objects.all().filter(qhname=qhname)
    else:
        if pcname != '':
            ts_list = Ts.objects.all().filter(pcname=pcname)
        else:
            ts_list = Ts.objects.all()
    return page_util(ts_list, page, limit)


def ts_info(request, id):
    ts_info = Ts.objects.get(id=id)
    result = json.loads(ts_info.toJSON())
    return JsonResponse(result, safe=False)


def ts_add(request):
    response = {}
    data = json.loads(request.body)
    ts = Ts.objects.create(
        id=uuid.uuid1(),
        pcname=data['pcname'],
        qhname=data['qhname'],
        state=data['state'])
    if not ts is None:
        response['status'] = 200
        response['msg'] = '服务器代理信息新建成功'
        return JsonResponse(response)
    else:
        response['status'] = 400
        response['msg'] = '服务器代理信息新建失败'
        return JsonResponse(response)


# 更服务器代理信息
def ts_update(request):
    response = {}
    data = json.loads(request.body)
    try:
        ts = Ts.objects.get(id=data['id'])
        ts.pcname = data['pcname']
        ts.qhname = data['qhname']
        ts.state = data['state']
        ts.save()
    except Exception:
        response['status'] = 400
        response['msg'] = '更新失败'
        return JsonResponse(response)
    response['status'] = 200
    response['msg'] = '更新成功'
    return JsonResponse(response)


# 删除服务器代理信息
def ts_delete(request, id):
    response = {}
    try:
        ts = Ts.objects.filter(id=id)
        ts.delete()
    except Exception:
        response['status'] = 400
        response['msg'] = '删除失败'
        return JsonResponse(response)
    response['status'] = 200
    response['msg'] = '删除成功'
    return JsonResponse(response)